<template>
	<view>
		<!-- <u-navbar :is-back="true" :is-fixed="true" title="新增订单"></u-navbar> -->
		<scroll-view scroll-y scroll-with-animation style="height: calc(100vh - 50px);" :show-scrollbar="false">

			<view class="tab-content">
				<view style=" background-color:#EFEDE9;">
					<view class="pl-2 pr-2 font-14 lineHight-40 font-weight-bold">服务信息</view>
				</view>
				<view class="pl-3 pr-2">
					<u-form :model="form" ref="uForm">
						<u-form-item :required="true" label-width="150" label="上游服务商">
							<u-input class="mr-3 " :disabled="true" v-model="userInfo.enterpriseName"
								input-align="right" />
						</u-form-item>
						<u-form-item :required="true" label-width="200" label="产品/服务名称" prop="productServeName">
							<u-input class="mr-3 " v-model="form.productServeName" input-align="right" />
						</u-form-item>
						<u-form-item :required="true" label-width="150" label="服务商名称" prop="serviceName">
							<u-input class="mr-3 " v-model="form.serviceName" input-align="right" />
						</u-form-item>
						<u-form-item :required="true" label-width="150" label="服务介绍" prop="serviceIntroduce">
							<u-input class="mr-3 " type="textarea" height="100" v-model="form.serviceIntroduce"
								input-align="right" />
						</u-form-item>
						<view class="text-right text-BEBFE8">({{ wordCount }} / {{maxCharacters }})</view>
						<u-form-item :required="true" label-width="180" label="服务介绍详情"
							style="padding-left: 10px; padding-right: 10px;">
							<u-upload ref="uUpload" :max-size="4 * 1024 * 1024" :form-data="{'biz':'temp'}"
								:header="header" @on-success="uploadSuccess" :action="getUploadUrl()"
								max-count="5"></u-upload>
						</u-form-item>
						<view class="font-12 text-FF0000 pl-1 pb-2">图片大小限制不能超过4MB,最多能上传五张图片</view>
						<u-form-item :required="true" label-width="200" label="服务价格(元)" prop="servicePrice">
							<u-input class="mr-3 " v-model="form.servicePrice" input-align="right" />
						</u-form-item>
						<!-- <u-form-item :required="true" label-width="150" label="服务流程">
							<u-input class="mr-3 " v-model="form.serviceFlow" input-align="right" />
						</u-form-item>
						<u-form-item :required="true" label-width="150" label="售后服务">
							<u-input class="mr-3 " v-model="form.serviceInform" input-align="right" />
						</u-form-item> -->

						<view style=" background-color:#EFEDE9;">
							<view class="pl-2 pr-2 font-14 lineHight-40 font-weight-bold">客户信息</view>
						</view>

						<!-- <u-form-item label-width="200" style="padding-right: 10px;" :required="true" label="涉农企业"
							prop="agricultureEnterpriseName">
							<u-input v-model="form.agricultureEnterpriseName" placeholder="请选择涉农企业" :type="type"
								input-align="right" :border="false" @click="showListCp = true" />
							<u-action-sheet :list="agricultureList" v-model="showListCp"
								@click="actionClickListCp"></u-action-sheet>
						</u-form-item> -->

						<u-form-item required label-width="180" label="上游服务商" prop="productInformId">
							<u-input v-model="form.agricultureEnterpriseName" placeholder="请选择上游服务商" :type="type"
								input-align="right" :border="false" @click="showNatureBusinessHandler" />
							<u-picker @confirm="selectNatureBusiness" mode="selector" v-model="showNatureBusiness"
								:default-selector="[0]" :range="natureBusinessList" range-key="text"></u-picker>
						</u-form-item>

						<u-form-item label-width="200" :required="true" label="联系方式">
							<u-input class="mr-3" :disabled="true" placeholder="请先选择涉农企业"
								v-model="form.agricultureUserPhone" input-align="right" />
						</u-form-item>
						<view style="background-color:#EFEDE9;">
							<view class=" font-14 lineHight-40 font-weight-bold">订单信息</view>
						</view>
						<!-- <u-form-item :label-style="labelStyle" label="订单编号" prop="name">
							<u-input class="mr-3" :disabled="true" v-model="form.name" input-align="right" />
						</u-form-item> -->
						<u-form-item required label-width="180" label="订单时间" prop="orderTime">
							<uni-calendar ref="calendarl" :start-date="currentDate" :insert="false" :lunar="true"
								@confirm="confirmName" :time-picker="true" />
							<view v-if="!selectedNameDate" class="text-999999 right-1-5 position-absolute"
								@click="openName">
								请选择日期</view>
							<view v-else class="right-1-5 position-absolute" @click="openName">{{ formattedOrderTime }}
							</view>
						</u-form-item>


						<u-form-item label-width="200" :required="true" label="订单进度" prop="orderSchedule">
							<u-input class="mr-3" v-model="form.orderSchedule" input-align="right" />
						</u-form-item>
						<u-form-item label-width="200" :required="true" label="订单评论" prop="orderEvaluation">
							<u-input class="mr-3" v-model="form.orderEvaluation" input-align="right" />
						</u-form-item>
					</u-form>
				</view>
			</view>

			<ferrButton @click="addOrderHandler" title="确认新增订单"></ferrButton>
		</scroll-view>
	</view>
</template>

<script>
	import ferrButton from "@/components/free-ui/ferr-button.vue";
	import calendar from "@/uni_modules/uni-calendar/components/uni-calendar/uni-calendar.vue"
	import $U from '@/common/free-lib/util.js';
	import $H from '@/common/free-lib/request.js';

	export default {
		components: {
			ferrButton,
			calendar
		},
		data() {
			return {
				rules: {
					productServeName: [{
						required: true,
						message: '产品/服务名称不能为空',
						trigger: ['change', 'blur'],
					}],
					servicePrice: [{
							required: true,
							message: '服务价格不能为空',
							trigger: ['change', 'blur'],
						},
						{
							validator: (rule, value, callback) => {
								// 允许数字和最多两位小数，并且不小于零
								const reg = /^(0|[1-9]\d*)(\.\d{1,2})?$/;
								if (!reg.test(value)) {
									callback(new Error('请输入非负数字，可以有最多两位小数'));
								} else {
									callback();
								}
							},
							trigger: ['change', 'blur'],
						}
					],
					serviceInform: [{
						required: true,
						message: '售后服务不能为空',
						trigger: ['change', 'blur'],
					}],
					agricultureEnterpriseName: [{
						required: true,
						message: '涉农企业不能为空',
						trigger: ['change', 'blur'],
					}],
					orderTime: [{
						required: true,
						message: '订单时间不能为空',
						trigger: ['change', 'blur'],
					}],
					orderSchedule: [{
						required: true,
						message: '订单进度不能为空',
						trigger: ['change', 'blur'],
					}],
					orderEvaluation: [{
						required: true,
						message: '订单评价不能为空',
						trigger: ['change', 'blur'],
					}],
					serviceName: [{
						required: true,
						message: '服务商名称不能为空',
						trigger: ['change', 'blur'],
					}],
					serviceIntroduce: [{
						required: true,
						message: '服务介绍不能为空',
						trigger: ['change', 'blur'],
					}]
				},
				form: {
					enterpriseName: $U.getStorage('enterpriseName'),
					upperUserId: $U.getStorage("id"),
					productServeName: "",
					servicePrice: "",
					serviceFlow: "",
					serviceInform: "",
					agricultureUserId: "",
					agricultureEnterpriseName: "",
					agricultureUserPhone: "",
					orderTime: "",
					orderSchedule: "",
					orderEvaluation: "",
					serviceName: "",
					serviceIntroduce: ""
				},
				value: '',
				type: 'select',
				selectedNameDate: null,

				valueListCp: '',
				agricultureList: [],
				showListCp: false,

				border: true,


				labelStyle: {
					paddingLeft: '13px',
					width: '130px'
				},

				form: {
					pageNo: 1,
					pageSize: 100,
					total: 0, // Total records
				},
				header: $H.getTokenHeader(),
				userInfo: {},


				showNatureBusiness: false,
				natureBusinessList: [],

				maxCharacters: 200
			};
		},

		onLoad() {
			this.queryAgricultureList();
			let store = uni.getStorageSync('userInfo')
			if (store) {
				this.userInfo = store
			}

		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		created() {
			this.setCurrentDate();
		},
		computed: {
			formattedOrderTime() {
				if (!this.form.orderTime) return '';
				return this.form.orderTime.split(' ')[0];
			},
			wordCount() {
				// 安全性检查，避免访问未定义的属性
				if (this.form.serviceIntroduce && typeof this.form.serviceIntroduce === 'string') {
					return this.form.serviceIntroduce.length;
				} else {
					return 0;
				}
			}
		},
		methods: {
			getUploadUrl(url) {
				return $H.getFullUrl('sys/common/upload');
			},
			uploadSuccess(data, index, lists, name) {
				if (data.success) {
					uni.showToast({
						title: '图片上传成功',
						icon: 'none'
					});
				} else {
					uni.showToast({
						title: data.message || '图片上传失败',
						icon: 'none'
					});
				}
			},
			addOrderHandler() {
				let files = [];
				files = this.$refs.uUpload.lists.filter(val => {
					return val.progress == 100;
				})
				if (files.length == 0) {
					uni.showToast({
						title: '请上传文件',
						icon: 'none'
					});
					return;
				}
				this.$refs.uForm.validate(valid => {
					if (valid) {
						uni.showLoading({
							title: '加载中'
						});
						if (this.form.orderTime) {
							const date = new Date(this.form.orderTime);
							this.form.orderTime =
								`${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} 00:00:00`;
						}
						const fileUrls = files.map(file => file.response.message).join(',');
						$H.post('/upper/upperMarketOrder/upper/addOrder', {
								...this.form,
								serviceIntroductionUrl: fileUrls
							}, {})
							.then(res => {
								if (res.code === 500) {
									uni.showToast({
										title: res.message || "服务价格不能小于0",
										icon: "none",
										duration: 4000
									});
								} else if (res.success) {
									uni.showToast({
										title: res.message || "添加成功",
										icon: "none",
										duration: 4000
									});
									setTimeout(() => {
										uni.navigateBack({
											delta: 1
										});
									}, 4000);
								} else {
									uni.showToast({
										title: res.message || "添加失败",
										icon: "none",
										duration: 4000
									});
								}
								uni.hideLoading();
							})
							.catch(error => {
								uni.hideLoading();
								console.error('请求出错', error); // 处理任何错误  
								uni.showToast({
									title: '新增失败',
									icon: 'none'
								});
							});
					} else {
						uni.showToast({
							title: '请填写完整信息',
							icon: 'none'
						});
					}
				});

			},

			showNatureBusinessHandler() {
				this.showNatureBusiness = true;
			},
			// selectNatureBusiness(e) {
			// 	this.valueProductName = this.natureBusinessList[e[0]].text;
			// 	this.form.upperUserId = this.natureBusinessList[e[0]].id;
			// },
			selectNatureBusiness(e) {
				this.form.agricultureEnterpriseName = this.natureBusinessList[e[0]].text
				this.form.agricultureUserId = this.natureBusinessList[e[0]].id;
				this.form.agricultureUserPhone = this.natureBusinessList[e[0]].phone;
			},

			openName() {
				this.$refs.calendarl.open();
			},
			confirmName(e) {
				this.selectedNameDate = e.fulldate;
				// 获取当前的日期
				const formattedDate = e.fulldate; // 只使用日期部分
				this.form.orderTime = formattedDate;

			},
			setCurrentDate() {
				const now = new Date();
				const year = now.getFullYear();
				const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 月份补齐两位数
				const day = now.getDate().toString().padStart(2, '0'); // 日期补齐两位数
				this.currentDate = `${year}-${month}-${day}`;
			},
			queryAgricultureList() {
				uni.showLoading({
					title: '加载中'
				});
				$H.get('/brand/user/selectUserList', {
						userType: 'AGRICULTURE',
						...this.form
					}, {})
					.then(res => {
						uni.hideLoading();
						if (res.result.length == 0) {
							uni.showToast({
								title: '涉农列表为空',
								icon: 'success'
							});
							return;
						}
						for (let i = 0; i < res.result.length; i++) {
							res.result[i]['text'] = res.result[i]['enterpriseName'];
						}
						console.log("res.result", res.result)
						this.natureBusinessList = res.result;
					})
					.catch(error => {
						console.error('请求出错', error); // 处理任何错误  
						uni.hideLoading();
					});
			}
		},
	};
</script>

<style>

</style>